package com.xiaoming.plugin.video_player;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.player.AliPlayer;
import com.aliyun.player.IPlayer;
import com.aliyun.player.alivcplayerexpand.constants.GlobalPlayerConfig;
import com.aliyun.player.alivcplayerexpand.listener.OnScreenCostingSingleTagListener;
import com.aliyun.player.alivcplayerexpand.listener.OnStoppedListener;
import com.aliyun.player.alivcplayerexpand.theme.Theme;
import com.aliyun.player.alivcplayerexpand.util.TimeFormater;
import com.aliyun.player.alivcplayerexpand.util.VidStsUtil;
import com.aliyun.player.alivcplayerexpand.view.choice.AlivcShowMoreDialog;
import com.aliyun.player.alivcplayerexpand.view.control.ControlView;
import com.aliyun.player.alivcplayerexpand.view.gesturedialog.BrightnessDialog;
import com.aliyun.player.alivcplayerexpand.view.more.AliyunShowMoreValue;
import com.aliyun.player.alivcplayerexpand.view.more.DanmakuSettingView;
import com.aliyun.player.alivcplayerexpand.view.more.ShowMoreView;
import com.aliyun.player.alivcplayerexpand.view.more.SpeedValue;
import com.aliyun.player.alivcplayerexpand.view.more.TrackInfoView;
import com.aliyun.player.alivcplayerexpand.view.softinput.SoftInputDialogFragment;
import com.aliyun.player.alivcplayerexpand.widget.AliyunVodPlayerView;
import com.aliyun.player.aliyunplayerbase.bean.AliyunMps;
import com.aliyun.player.aliyunplayerbase.bean.AliyunPlayAuth;
import com.aliyun.player.aliyunplayerbase.bean.AliyunSts;
import com.aliyun.player.aliyunplayerbase.net.GetAuthInformation;
import com.aliyun.player.aliyunplayerbase.util.AliyunScreenMode;
import com.aliyun.player.aliyunplayerbase.view.tipsview.ErrorInfo;
import com.aliyun.player.aliyunplayerbase.view.tipsview.OnTipsViewBackClickListener;
import com.aliyun.player.aliyunplayerbase.view.tipsview.TipsView;
import com.aliyun.player.bean.ErrorCode;
import com.aliyun.player.bean.InfoBean;
import com.aliyun.player.bean.InfoCode;
import com.aliyun.player.nativeclass.CacheConfig;
import com.aliyun.player.nativeclass.MediaInfo;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.nativeclass.TrackInfo;
import com.aliyun.player.source.StsInfo;
import com.aliyun.player.source.UrlSource;
import com.aliyun.player.source.VidAuth;
import com.aliyun.player.source.VidMps;
import com.aliyun.player.source.VidSts;
import com.aliyun.svideo.common.utils.FastClickUtil;
import com.aliyun.svideo.common.utils.FileUtils;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.taobao.weex.ui.component.WXComponentProp;
import com.xiaoming.plugin.video_player.model.Result;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.dcloud.feature.uniapp.UniSDKInstance;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.ui.action.AbsComponentData;
import io.dcloud.feature.uniapp.ui.component.AbsVContainer;
import io.dcloud.feature.uniapp.ui.component.UniComponent;

public class XmAliyunVodPlayerView extends UniComponent<AliyunVodPlayerView> {
    private static final String TAG = XmAliyunVodPlayerView.class.getSimpleName();

    private AliyunVodPlayerView mAliyunVodPlayerView = null;

    /**
     * 当前正在播放的videoId，跟下载有关
     */
    private String mCurrentVideoId;
    private boolean mNeedOnlyFullScreen;

    private ErrorInfo currentError = ErrorInfo.Normal;

    /**
     * 更多Dialog
     */
    private AlivcShowMoreDialog showMoreDialog;
    /**
     * 弹幕设置Dialog
     */
    private AlivcShowMoreDialog danmakuShowMoreDialog;
    /**
     * 投屏选择Dialog
     */
    private AlivcShowMoreDialog screenShowMoreDialog;
    /**
     * 弹幕设置View
     */
    private DanmakuSettingView mDanmakuSettingView;
    /**
     * 点击发送弹幕的画笔弹出的dialog
     */
    private SoftInputDialogFragment mSoftInputDialogFragment;

    //弹幕透明度、显示区域、速率progress
    private int mAlphProgress = 0, mRegionProgress = 0, mSpeedProgress = 30;
    /**
     * 是否鉴权过期
     */
    private boolean mIsTimeExpired = false;
    /**
     * 当前系统屏幕亮度
     */
    private int mCurrentBrightValue;

    private AliyunScreenMode currentScreenMode = AliyunScreenMode.Small;

    @Override
    protected AliyunVodPlayerView initComponentHostView(@NonNull Context context) {
        this.mAliyunVodPlayerView = new AliyunVodPlayerView(context);
        GlobalPlayerConfig.IS_BARRAGE = false;
        initAliyunPlayerView();
        initPlayerConfig();
        mCurrentBrightValue = getCurrentBrightValue();
        return mAliyunVodPlayerView;
    }

    private void initAliyunPlayerView() {
        //保持屏幕敞亮
        mAliyunVodPlayerView.setKeepScreenOn(true);
        mAliyunVodPlayerView.setTheme(Theme.Blue);
        mAliyunVodPlayerView.setAutoPlay(true);
        mAliyunVodPlayerView.needOnlyFullScreenPlay(mNeedOnlyFullScreen);
        mAliyunVodPlayerView.setOnPreparedListener(new MyPrepareListener(this));
        mAliyunVodPlayerView.setNetConnectedListener(new MyNetConnectedListener(this));
        mAliyunVodPlayerView.setOnCompletionListener(new MyCompletionListener(this));
        mAliyunVodPlayerView.setOnFirstFrameStartListener(new MyFrameInfoListener(this));
        mAliyunVodPlayerView.setOnTrackChangedListener(new MyOnTrackChangedListener(this));
        mAliyunVodPlayerView.setOnStoppedListener(new MyStoppedListener(this));
        mAliyunVodPlayerView.setOrientationChangeListener(new MyOrientationChangeListener(this));
        mAliyunVodPlayerView.setProgressChangeListener(new MyProgressChangeListener(this));
        mAliyunVodPlayerView.setOnControlViewHideListener(new MyControlViewHideListene(this));
        mAliyunVodPlayerView.setOnLoadingListener(new MyLoadingStatusListener(this));
        mAliyunVodPlayerView.setOnTimeExpiredErrorListener(new MyOnTimeExpiredErrorListener(this));
        mAliyunVodPlayerView.setOnShowMoreClickListener(new MyShowMoreClickLisener(this));
        mAliyunVodPlayerView.setOnPlayStateBtnClickListener(new MyPlayStateBtnClickListener(this));
        mAliyunVodPlayerView.setOnSeekCompleteListener(new MySeekCompleteListener(this));
        mAliyunVodPlayerView.setOnSeekStartListener(new MySeekStartListener(this));
        mAliyunVodPlayerView.setOnFinishListener(new MyOnFinishListener(this));
        mAliyunVodPlayerView.setOnScreenCostingSingleTagListener(new MyOnScreenCostingSingleTagListener(this));
        mAliyunVodPlayerView.setOnScreenBrightness(new MyOnScreenBrightnessListener(this));
        mAliyunVodPlayerView.setSoftKeyHideListener(new MyOnSoftKeyHideListener(this));
        mAliyunVodPlayerView.setOnErrorListener(new MyOnErrorListener(this));
        mAliyunVodPlayerView.setScreenBrightness(BrightnessDialog.getActivityBrightness((Activity) mUniSDKInstance.getContext()));
        mAliyunVodPlayerView.setOnTrackInfoClickListener(new MyOnTrackInfoClickListener(this));
        mAliyunVodPlayerView.setOnInfoListener(new MyOnInfoListener(this));
        mAliyunVodPlayerView.setOutOnSeiDataListener(new MyOnSeiDataListener(this));
        mAliyunVodPlayerView.setOnTipClickListener(new MyOnTipClickListener(this));
        mAliyunVodPlayerView.setOnTipsViewBackClickListener(new MyOnTipsViewBackClickListener(this));
        mAliyunVodPlayerView.setOutOnVerifyTimeExpireCallback(new MyOnVerifyStsCallback(this));
        mAliyunVodPlayerView.enableNativeLog();
        mAliyunVodPlayerView.setScreenBrightness(mCurrentBrightValue);
        mAliyunVodPlayerView.startNetWatch();
    }

    /**
     * 初始化播放配置
     */
    private void initPlayerConfig() {
        if (mAliyunVodPlayerView != null) {
            //界面设置
            mAliyunVodPlayerView.setEnableHardwareDecoder(GlobalPlayerConfig.mEnableHardDecodeType);
            mAliyunVodPlayerView.setRenderMirrorMode(GlobalPlayerConfig.mMirrorMode);
            mAliyunVodPlayerView.setRenderRotate(GlobalPlayerConfig.mRotateMode);

            //播放配置设置
            PlayerConfig playerConfig = mAliyunVodPlayerView.getPlayerConfig();
            playerConfig.mStartBufferDuration = GlobalPlayerConfig.PlayConfig.mStartBufferDuration;
            playerConfig.mHighBufferDuration = GlobalPlayerConfig.PlayConfig.mHighBufferDuration;
            playerConfig.mMaxBufferDuration = GlobalPlayerConfig.PlayConfig.mMaxBufferDuration;
            playerConfig.mMaxDelayTime = GlobalPlayerConfig.PlayConfig.mMaxDelayTime;
            playerConfig.mNetworkTimeout = GlobalPlayerConfig.PlayConfig.mNetworkTimeout;
            playerConfig.mMaxProbeSize = GlobalPlayerConfig.PlayConfig.mMaxProbeSize;
            playerConfig.mReferrer = GlobalPlayerConfig.PlayConfig.mReferrer;
            playerConfig.mHttpProxy = GlobalPlayerConfig.PlayConfig.mHttpProxy;
            playerConfig.mNetworkRetryCount = GlobalPlayerConfig.PlayConfig.mNetworkRetryCount;
            playerConfig.mEnableSEI = GlobalPlayerConfig.PlayConfig.mEnableSei;
            playerConfig.mClearFrameWhenStop = GlobalPlayerConfig.PlayConfig.mEnableClearWhenStop;
            mAliyunVodPlayerView.setPlayerConfig(playerConfig);

            //缓存设置
            initCacheConfig();
            Log.e(TAG, "cache dir : " + GlobalPlayerConfig.PlayCacheConfig.mDir
                    + " startBufferDuration = " + GlobalPlayerConfig.PlayConfig.mStartBufferDuration
                    + " highBufferDuration = " + GlobalPlayerConfig.PlayConfig.mHighBufferDuration
                    + " maxBufferDuration = " + GlobalPlayerConfig.PlayConfig.mMaxBufferDuration
                    + " maxDelayTime = " + GlobalPlayerConfig.PlayConfig.mMaxDelayTime
                    + " enableCache = " + GlobalPlayerConfig.PlayCacheConfig.mEnableCache
                    + " --- mMaxDurationS = " + GlobalPlayerConfig.PlayCacheConfig.mMaxDurationS
                    + " --- mMaxSizeMB = " + GlobalPlayerConfig.PlayCacheConfig.mMaxSizeMB);
        }
    }

    private void initCacheConfig() {
        CacheConfig cacheConfig = new CacheConfig();
        GlobalPlayerConfig.PlayCacheConfig.mDir = FileUtils.getDir(mUniSDKInstance.getContext()) + GlobalPlayerConfig.CACHE_DIR_PATH;
        cacheConfig.mEnable = GlobalPlayerConfig.PlayCacheConfig.mEnableCache;
        cacheConfig.mDir = GlobalPlayerConfig.PlayCacheConfig.mDir;
        cacheConfig.mMaxDurationS = GlobalPlayerConfig.PlayCacheConfig.mMaxDurationS;
        cacheConfig.mMaxSizeMB = GlobalPlayerConfig.PlayCacheConfig.mMaxSizeMB;

        mAliyunVodPlayerView.setCacheConfig(cacheConfig);
    }

    /**
     * 仅当系统的亮度模式是非自动模式的情况下，获取当前屏幕亮度值[0, 255].
     * 如果是自动模式，那么该方法获得的值不正确。
     */
    private int getCurrentBrightValue() {
        int nowBrightnessValue = 0;
        ContentResolver resolver = mUniSDKInstance.getContext().getContentResolver();
        try {
            nowBrightnessValue = android.provider.Settings.System.getInt(resolver,
                    Settings.System.SCREEN_BRIGHTNESS, 255);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }

    @WXComponentProp(name = "UrlSource")
    public void initDataSource(JSONObject options) {
        if (options == null || options.isEmpty()) {
            Map<String, Object> params = new HashMap<>();
            //目前uni限制 参数需要放入到"detail"中 否则会被清理
            params.put("detail", "UrlSource配置为空！");
            fireEvent("onError", params);
        }
        String videoPath = options.getString("url");
        if (TextUtils.isEmpty(videoPath)) {
            Map<String, Object> params = new HashMap<>();
            //目前uni限制 参数需要放入到"detail"中 否则会被清理
            params.put("detail", "UrlSource地址为空！");
            fireEvent("onError", params);
            return;
        }
        UrlSource urlSource = new UrlSource();
        urlSource.setCoverPath(options.getString("cover"));
        urlSource.setTitle(options.getString("title"));
        mCurrentVideoId = "";
        if (TextUtils.isEmpty(videoPath)) {
            urlSource.setUri(GlobalPlayerConfig.mUrlPath);
        } else {
            urlSource.setUri(videoPath);
        }
        mAliyunVodPlayerView.setLocalSource(urlSource);
        if (!TextUtils.isEmpty(urlSource.getCoverPath())) {
            mAliyunVodPlayerView.setCoverUri(urlSource.getCoverPath());
        }
        if (!TextUtils.isEmpty(urlSource.getTitle())) {
            mAliyunVodPlayerView.setTitleBarCanShow(true);
        }
    }
//    /**
//     * 播放方式
//     */
//    private void initDataSource() {
//        GlobalPlayerConfig.PLAYTYPE mCurrentPlayType = GlobalPlayerConfig.mCurrentPlayType;
//        if (mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.AUTH) {
//            VidAuth vidAuth = getVidAuth(GlobalPlayerConfig.mVid);
//            mCurrentVideoId = GlobalPlayerConfig.mVid;
//            mAliyunVodPlayerView.setAuthInfo(vidAuth);
//        } else if (mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.STS) {
//            VidSts vidSts = getVidSts(GlobalPlayerConfig.mVid);
//            mCurrentVideoId = GlobalPlayerConfig.mVid;
//            mAliyunVodPlayerView.setVidSts(vidSts);
//        } else if (mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.URL) {
//            UrlSource urlSource = new UrlSource();
//            mCurrentVideoId = "";
//            if (TextUtils.isEmpty(mLocalVideoPath)) {
//                urlSource.setUri(GlobalPlayerConfig.mUrlPath);
//            } else {
//                urlSource.setUri(mLocalVideoPath);
//            }
//            mAliyunVodPlayerView.setLocalSource(urlSource);
//        } else if (mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.MPS) {
//            VidMps vidMps = getVidMps(GlobalPlayerConfig.mVid);
//            mCurrentVideoId = GlobalPlayerConfig.mVid;
//            mAliyunVodPlayerView.setVidMps(vidMps);
//        } else if (mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.LIVE_STS) {
//            LiveSts liveSts = getLiveSts(GlobalPlayerConfig.mLiveStsUrl);
//            mAliyunVodPlayerView.setLiveStsDataSource(liveSts);
//        } else {
//            //default
//            currentVidItemPosition = 0;
//            loadPlayList();
//        }
//
////        if (mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.STS
////                || mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.AUTH
////                || mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.DEFAULT) {
////            mDownloadImageView.setVisibility(View.VISIBLE);
////        } else {
////            mDownloadImageView.setVisibility(View.GONE);
////        }
//    }

    public XmAliyunVodPlayerView(UniSDKInstance instance, AbsVContainer parent, AbsComponentData componentData) {
        super(instance, parent, componentData);
    }

    private static class MyPrepareListener implements IPlayer.OnPreparedListener {

        private WeakReference<XmAliyunVodPlayerView> activityWeakReference;

        public MyPrepareListener(XmAliyunVodPlayerView skinActivity) {
            activityWeakReference = new WeakReference<>(skinActivity);
        }

        @Override
        public void onPrepared() {
            XmAliyunVodPlayerView activity = activityWeakReference.get();
            if (activity != null) {
                activity.onPrepared();
            }
        }
    }

    /**
     * 准备成功
     */
    private void onPrepared() {
//        Toast.makeText(mUniSDKInstance.getContext(), R.string.toast_prepare_success, Toast.LENGTH_SHORT).show();
        if (mAliyunVodPlayerView != null) {
            MediaInfo mediaInfo = mAliyunVodPlayerView.getMediaInfo();
            if (mediaInfo != null) {
                mCurrentVideoId = mediaInfo.getVideoId();
            }
        }
    }

    /**
     * 判断是否有网络的监听
     */
    private static class MyNetConnectedListener implements AliyunVodPlayerView.NetConnectedListener {
        WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyNetConnectedListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onReNetConnected(boolean isReconnect) {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onReNetConnected(isReconnect);
            }
        }

        @Override
        public void onNetUnConnected() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onNetUnConnected();
            }
        }
    }

    /**
     * 网络未连接
     */
    private void onNetUnConnected() {
        currentError = ErrorInfo.UnConnectInternet;
//        if (aliyunDownloadMediaInfoList != null && aliyunDownloadMediaInfoList.size() > 0) {
//            ConcurrentLinkedQueue<AliyunDownloadMediaInfo> allDownloadMediaInfo = new ConcurrentLinkedQueue<>();
//            List<AliyunDownloadMediaInfo> mediaInfos = downloadDataProvider.getAllDownloadMediaInfo();
//            allDownloadMediaInfo.addAll(mediaInfos);
//            downloadManager.stopDownloads(allDownloadMediaInfo);
//        }
    }

    /**
     * 网络已连接
     *
     * @param isReconnect
     */
    private void onReNetConnected(boolean isReconnect) {
        currentError = ErrorInfo.Normal;
    }

    private static class MyCompletionListener implements IPlayer.OnCompletionListener {

        private WeakReference<XmAliyunVodPlayerView> activityWeakReference;

        public MyCompletionListener(XmAliyunVodPlayerView skinActivity) {
            activityWeakReference = new WeakReference<XmAliyunVodPlayerView>(skinActivity);
        }

        @Override
        public void onCompletion() {

            XmAliyunVodPlayerView activity = activityWeakReference.get();
            if (activity != null) {
                activity.onCompletion();
            }
        }
    }

    private void onCompletion() {
        //Toast.makeText(mUniSDKInstance.getContext(), R.string.toast_play_compleion, Toast.LENGTH_SHORT).show();
        fireEvent("onCompletion");
        // TODO: 2021/6/2 0002 貌似暂时用不上
//        hideAllDialog();

//        // 当前视频播放结束, 播放下一个视频
//        if (GlobalPlayerConfig.mCurrentPlayType.equals(GlobalPlayerConfig.PLAYTYPE.DEFAULT)) {
//            // TODO: 2021/6/2 0002 后续再设计
////            onNext();
//        } else {
//
//        }
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.showReplay();
        }
    }

    private static class MyFrameInfoListener implements IPlayer.OnRenderingStartListener {

        private WeakReference<XmAliyunVodPlayerView> activityWeakReference;

        public MyFrameInfoListener(XmAliyunVodPlayerView skinActivity) {
            activityWeakReference = new WeakReference<>(skinActivity);
        }

        @Override
        public void onRenderingStart() {
            XmAliyunVodPlayerView activity = activityWeakReference.get();
            if (activity != null) {
                activity.onFirstFrameStart();
            }
        }
    }

    private void onFirstFrameStart() {
        fireEvent("onFirstFrameStart");
    }

    private static class MyOnTrackChangedListener implements IPlayer.OnTrackChangedListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnTrackChangedListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onChangedSuccess(TrackInfo trackInfo) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.changeTrackSuccess(trackInfo);
            }
        }

        @Override
        public void onChangedFail(TrackInfo trackInfo, com.aliyun.player.bean.ErrorInfo errorInfo) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.changeTrackFail(trackInfo, errorInfo);
            }
        }
    }

    private void changeTrackFail(TrackInfo trackInfo, com.aliyun.player.bean.ErrorInfo errorInfo) {
        if (showMoreDialog != null && showMoreDialog.isShowing()) {
            showMoreDialog.dismiss();
        }
//        Toast.makeText(mUniSDKInstance.getContext(), mUniSDKInstance.getContext().getString(R.string.alivc_player_track_change_error, errorInfo.getCode(), errorInfo.getMsg()), Toast.LENGTH_SHORT).show();
    }

    private void changeTrackSuccess(TrackInfo trackInfo) {
        if (trackInfo == null) {
            return;
        }
        if (showMoreDialog != null && showMoreDialog.isShowing()) {
            showMoreDialog.dismiss();
        }
        if (trackInfo.getType() == TrackInfo.Type.TYPE_VIDEO) {
            //码率
//            Toast.makeText(mUniSDKInstance.getContext(), mUniSDKInstance.getContext().getString(R.string.alivc_player_track_bitrate_change_success, trackInfo.getVideoBitrate() + ""), Toast.LENGTH_SHORT).show();
        } else if (trackInfo.getType() == TrackInfo.Type.TYPE_VOD) {
//            Toast.makeText(mUniSDKInstance.getContext(), mUniSDKInstance.getContext().getString(R.string.alivc_player_track_definition_change_success, trackInfo.getVodDefinition()), Toast.LENGTH_SHORT).show();
        } else {
//            Toast.makeText(mUniSDKInstance.getContext(), mUniSDKInstance.getContext().getString(R.string.alivc_player_track_change_success, trackInfo.getDescription()), Toast.LENGTH_SHORT).show();
        }
    }

    private static class MyStoppedListener implements OnStoppedListener {

        private WeakReference<XmAliyunVodPlayerView> activityWeakReference;

        public MyStoppedListener(XmAliyunVodPlayerView skinActivity) {
            activityWeakReference = new WeakReference<>(skinActivity);
        }

        @Override
        public void onStop() {
            XmAliyunVodPlayerView activity = activityWeakReference.get();
            if (activity != null) {
                activity.onStopped();
            }
        }
    }


    private void onStopped() {
//        Toast.makeText(mUniSDKInstance.getContext(), R.string.log_play_stopped, Toast.LENGTH_SHORT).show();
    }

    private static class MyOrientationChangeListener implements AliyunVodPlayerView.OnOrientationChangeListener {

        private final WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOrientationChangeListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void orientationChange(boolean from, AliyunScreenMode currentMode) {
            XmAliyunVodPlayerView activity = weakReference.get();

            if (activity != null) {
                if (currentMode == AliyunScreenMode.Small) {
                    //如果播放本地视频，切换到小屏后，直接关闭
                    // TODO: 2021/6/2 0002 这里需要优化
//                    activity.finish();

                    activity.onExitFullScreen();
                } else {
                    activity.onEnterFullScreen();
                    // TODO: 2021/6/2 0002 下载功能暂停不做
//                    activity.hideDownloadDialog(from, currentMode);
                    activity.hideShowMoreDialog(from, currentMode);
                    activity.hideDanmakuSettingDialog(from, currentMode);
                    activity.hideScreenSostDialog(from, currentMode);
                }
            }
        }
    }

    private static class MyProgressChangeListener implements AliyunVodPlayerView.OnProgressChangeListener {

        private final WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyProgressChangeListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void progressChange(int currentPosition, int duration) {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.progressChange(currentPosition, duration);
            }
        }
    }

    public void progressChange(int currentPosition, int duration) {
        Map<String, Integer> data = new HashMap<>();
        data.put("currentPosition", currentPosition);
        data.put("duration", duration);
        Map<String, Object> params = new HashMap<>();
        //目前uni限制 参数需要放入到"detail"中 否则会被清理
        params.put("detail", data);
        fireEvent("onProgress");
    }

    private static class MyControlViewHideListene implements ControlView.OnControlViewHideListener {

        private final WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyControlViewHideListene(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onControlViewHide() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onControlViewHide();
            }
        }

        @Override
        public void onControlViewShow() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onControlViewShow();
            }
        }
    }

    public void onControlViewHide() {
        fireEvent("onControlViewHide");
    }

    public void onControlViewShow() {
        fireEvent("onControlViewShow");
    }

    private static class MyLoadingStatusListener implements IPlayer.OnLoadingStatusListener {

        private final WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyLoadingStatusListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onLoadingBegin() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onLoadingBegin();
            }
        }

        @Override
        public void onLoadingProgress(int i, float v) {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onLoadingProgress(i, v);
            }
        }

        @Override
        public void onLoadingEnd() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onLoadingEnd();
            }
        }
    }

    public void onLoadingBegin() {
        fireEvent("onLoadingBegin");
    }

    public void onLoadingProgress(int i, float v) {
        Map<String, Object> params = new HashMap<>();
        //目前uni限制 参数需要放入到"detail"中 否则会被清理
        params.put("detail", i);
        fireEvent("onLoadingProgress", params);
    }

    public void onLoadingEnd() {
        fireEvent("onLoadingEnd");
    }

    public void onEnterFullScreen() {
        fireEvent("enterFullScreen");
    }

    public void onExitFullScreen() {
        fireEvent("exitFullScreen");
    }

//    private void hideDownloadDialog(boolean from, AliyunScreenMode currentMode) {
//
//        if (mAlivcListSelectorDialogFragment != null) {
//            if (currentScreenMode != currentMode) {
//                mAlivcListSelectorDialogFragment.dismiss();
//                currentScreenMode = currentMode;
//            }
//        }
//        mDownloadListTextView.setVisibility(currentMode == AliyunScreenMode.Small ? View.VISIBLE : View.GONE);
//    }

    //隐藏更多对话框
    private void hideShowMoreDialog(boolean from, AliyunScreenMode currentMode) {
        if (showMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                showMoreDialog.dismiss();
                currentScreenMode = currentMode;
            }
        }
    }

    //隐藏弹幕对话框
    private void hideDanmakuSettingDialog(boolean fromUser, AliyunScreenMode currentMode) {
        if (danmakuShowMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                danmakuShowMoreDialog.dismiss();
                currentScreenMode = currentMode;
            }
        }
    }

    private void hideScreenSostDialog(boolean fromUser, AliyunScreenMode currentMode) {
        if (screenShowMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                screenShowMoreDialog.dismiss();
                currentScreenMode = currentMode;
            }
        }
    }

    public static class MyOnTimeExpiredErrorListener implements AliyunVodPlayerView.OnTimeExpiredErrorListener {

        WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnTimeExpiredErrorListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onTimeExpiredError() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onTimExpiredError();
            }
        }
    }

    /**
     * 鉴权过期
     */
    private void onTimExpiredError() {
        VidStsUtil.getVidSts(GlobalPlayerConfig.mVid, new RetryExpiredSts(this));
    }

    /**
     * 因为鉴权过期,而去重新鉴权
     */
    private static class RetryExpiredSts implements VidStsUtil.OnStsResultListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public RetryExpiredSts(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onSuccess(String vid, String akid, String akSecret, String token) {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onStsRetrySuccess(vid, akid, akSecret, token);
            }
        }

        @Override
        public void onFail() {

        }
    }

    private void onStsRetrySuccess(String mVid, String akid, String akSecret, String token) {
        GlobalPlayerConfig.mVid = mVid;
        GlobalPlayerConfig.mStsAccessKeyId = akid;
        GlobalPlayerConfig.mStsAccessKeySecret = akSecret;
        GlobalPlayerConfig.mStsSecurityToken = token;

        // TODO: 2021/6/2 0002 暂时不做
//        inRequest = false;
//        mIsTimeExpired = false;
//
//        VidSts vidSts = getVidSts(mVid);
//        mAliyunVodPlayerView.setVidSts(vidSts);
    }

    private static class MyShowMoreClickLisener implements ControlView.OnShowMoreClickListener {
        WeakReference<XmAliyunVodPlayerView> weakReference;

        MyShowMoreClickLisener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void showMore() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                if (FastClickUtil.isFastClick()) {
                    return;
                }
                activity.showMore();
            }
        }
    }

    private void showMore() {
        showMoreDialog = new AlivcShowMoreDialog(mUniSDKInstance.getContext());
        AliyunShowMoreValue moreValue = new AliyunShowMoreValue();
        moreValue.setSpeed(mAliyunVodPlayerView.getCurrentSpeed());
        moreValue.setVolume((int) mAliyunVodPlayerView.getCurrentVolume());
        moreValue.setScaleMode(mAliyunVodPlayerView.getScaleMode());
        moreValue.setLoop(mAliyunVodPlayerView.isLoop());

        ShowMoreView showMoreView = new ShowMoreView(mUniSDKInstance.getContext(), moreValue);
        showMoreDialog.setContentView(showMoreView);
        showMoreDialog.show();

        showMoreView.setOnScreenCastButtonClickListener(new ShowMoreView.OnScreenCastButtonClickListener() {
            @Override
            public void onScreenCastClick() {
            }
        });

        showMoreView.setOnBarrageButtonClickListener(new ShowMoreView.OnBarrageButtonClickListener() {
            @Override
            public void onBarrageClick() {
                if (showMoreDialog != null && showMoreDialog.isShowing()) {
                    showMoreDialog.dismiss();
                }
                showDanmakuSettingView();
            }
        });

        showMoreView.setOnSpeedCheckedChangedListener(new ShowMoreView.OnSpeedCheckedChangedListener() {
            @Override
            public void onSpeedChanged(RadioGroup group, int checkedId) {
                // 点击速度切换
                if (checkedId == R.id.rb_speed_normal) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.One);
                } else if (checkedId == R.id.rb_speed_onequartern) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.OneQuartern);
                } else if (checkedId == R.id.rb_speed_onehalf) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.OneHalf);
                } else if (checkedId == R.id.rb_speed_twice) {
                    mAliyunVodPlayerView.changeSpeed(SpeedValue.Twice);
                }

            }
        });

        showMoreView.setOnScaleModeCheckedChangedListener(new ShowMoreView.OnScaleModeCheckedChangedListener() {
            @Override
            public void onScaleModeChanged(RadioGroup group, int checkedId) {
                //切换画面比例
                IPlayer.ScaleMode mScaleMode;
                if (checkedId == R.id.rb_scale_aspect_fit) {
                    mScaleMode = IPlayer.ScaleMode.SCALE_ASPECT_FIT;
                } else if (checkedId == R.id.rb_scale_aspect_fill) {
                    mScaleMode = IPlayer.ScaleMode.SCALE_ASPECT_FILL;
                } else if (checkedId == R.id.rb_scale_to_fill) {
                    mScaleMode = IPlayer.ScaleMode.SCALE_TO_FILL;
                } else {
                    mScaleMode = IPlayer.ScaleMode.SCALE_ASPECT_FIT;
                }
                mAliyunVodPlayerView.setScaleMode(mScaleMode);
            }
        });

        showMoreView.setOnLoopCheckedChangedListener(new ShowMoreView.OnLoopCheckedChangedListener() {
            @Override
            public void onLoopChanged(RadioGroup group, int checkedId) {
                boolean isLoop;
                if (checkedId == R.id.rb_loop_open) {
                    isLoop = true;
                } else {
                    isLoop = false;
                }
                mAliyunVodPlayerView.setLoop(isLoop);
            }
        });

        /**
         * 初始化亮度
         */
        if (mAliyunVodPlayerView != null) {
            showMoreView.setBrightness(mAliyunVodPlayerView.getScreenBrightness());
        }
        // 亮度seek
        showMoreView.setOnLightSeekChangeListener(new ShowMoreView.OnLightSeekChangeListener() {
            @Override
            public void onStart(SeekBar seekBar) {

            }

            @Override
            public void onProgress(SeekBar seekBar, int progress, boolean fromUser) {
                setWindowBrightness(progress);
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setScreenBrightness(progress);
                }
            }

            @Override
            public void onStop(SeekBar seekBar) {

            }
        });

        /**
         * 初始化音量
         */
        if (mAliyunVodPlayerView != null) {
            showMoreView.setVoiceVolume(mAliyunVodPlayerView.getCurrentVolume());
        }
        showMoreView.setOnVoiceSeekChangeListener(new ShowMoreView.OnVoiceSeekChangeListener() {
            @Override
            public void onStart(SeekBar seekBar) {

            }

            @Override
            public void onProgress(SeekBar seekBar, int progress, boolean fromUser) {
                mAliyunVodPlayerView.setCurrentVolume(progress / 100.00f);
            }

            @Override
            public void onStop(SeekBar seekBar) {

            }
        });

    }


    /**
     * 显示弹幕设置对话框
     */
    private void showDanmakuSettingView() {
        danmakuShowMoreDialog = new AlivcShowMoreDialog(mUniSDKInstance.getContext());
        mDanmakuSettingView = new DanmakuSettingView(mUniSDKInstance.getContext());
        mDanmakuSettingView.setAlphaProgress(mAlphProgress);
        mDanmakuSettingView.setSpeedProgress(mSpeedProgress);
        mDanmakuSettingView.setRegionProgress(mRegionProgress);
        danmakuShowMoreDialog.setContentView(mDanmakuSettingView);
        danmakuShowMoreDialog.show();

        //透明度
        mDanmakuSettingView.setOnAlphaSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mAlphProgress = progress;
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuAlpha(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //显示区域
        mDanmakuSettingView.setOnRegionSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mRegionProgress = progress;
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuRegion(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //速率
        mDanmakuSettingView.setOnSpeedSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mSpeedProgress = progress;
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuSpeed(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //恢复默认
        mDanmakuSettingView.setOnDefaultListener(new DanmakuSettingView.OnDefaultClickListener() {
            @Override
            public void onDefaultClick() {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuDefault();
                }
            }
        });

    }

    /**
     * 设置屏幕亮度
     */
    private void setWindowBrightness(int brightness) {
        Window window = ((Activity) mUniSDKInstance.getContext()).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness / 100.00f;
        window.setAttributes(lp);
    }

    private static class MyPlayStateBtnClickListener implements AliyunVodPlayerView.OnPlayStateBtnClickListener {
        WeakReference<XmAliyunVodPlayerView> weakReference;

        MyPlayStateBtnClickListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onPlayBtnClick(int playerState) {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onPlayStateSwitch(playerState);
            }
        }
    }

    /**
     * 播放状态切换
     */
    private void onPlayStateSwitch(int playerState) {
        if (playerState == IPlayer.started) {
            fireEvent("onPlay");
        } else if (playerState == IPlayer.paused) {
            fireEvent("onPause");
        }
    }


    private static class MySeekCompleteListener implements IPlayer.OnSeekCompleteListener {
        WeakReference<XmAliyunVodPlayerView> weakReference;

        MySeekCompleteListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onSeekComplete() {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onSeekComplete();
            }
        }
    }

    private void onSeekComplete() {

    }

    private static class MySeekStartListener implements AliyunVodPlayerView.OnSeekStartListener {
        WeakReference<XmAliyunVodPlayerView> weakReference;

        MySeekStartListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onSeekStart(int position) {
            XmAliyunVodPlayerView activity = weakReference.get();
            if (activity != null) {
                activity.onSeekStart(position);
            }
        }
    }

    private void onSeekStart(int position) {
    }

    private static class MyOnFinishListener implements AliyunVodPlayerView.OnFinishListener {

        WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnFinishListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onFinishClick() {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                // TODO: 2021/6/2 0002 这里不能finish
//                aliyunPlayerSkinActivity.finish();
            }
        }
    }

    private static class MyOnScreenCostingSingleTagListener implements OnScreenCostingSingleTagListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        private MyOnScreenCostingSingleTagListener(XmAliyunVodPlayerView aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void onScreenCostingSingleTag() {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.screenCostingSingleTag();
            }
        }
    }

    private void screenCostingSingleTag() {
        if (screenShowMoreDialog != null && screenShowMoreDialog.isShowing()) {
            screenShowMoreDialog.dismiss();
        }
    }

    private static class MyOnScreenBrightnessListener implements AliyunVodPlayerView.OnScreenBrightnessListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnScreenBrightnessListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onScreenBrightness(int brightness) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.setWindowBrightness(brightness);
                if (aliyunPlayerSkinActivity.mAliyunVodPlayerView != null) {
                    aliyunPlayerSkinActivity.mAliyunVodPlayerView.setScreenBrightness(brightness);
                }
            }
        }
    }

    /**
     * 软键盘隐藏监听
     */
    private static class MyOnSoftKeyHideListener implements AliyunVodPlayerView.OnSoftKeyHideListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnSoftKeyHideListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void softKeyHide() {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.hideSoftKeyBoard();
            }
        }

        @Override
        public void onClickPaint() {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onSoftKeyShow();

            }
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftKeyBoard() {
        View view = ((Activity) mUniSDKInstance.getContext()).getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) mUniSDKInstance.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void onSoftKeyShow() {
        if (mSoftInputDialogFragment != null) {
            mSoftInputDialogFragment.show(((FragmentActivity) mUniSDKInstance.getContext()).getSupportFragmentManager(), "SoftInputDialogFragment");
        }
    }

    /**
     * 播放器出错监听
     */
    private static class MyOnErrorListener implements IPlayer.OnErrorListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnErrorListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onError(com.aliyun.player.bean.ErrorInfo errorInfo) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onError(errorInfo);
            }
        }
    }

    private void onError(com.aliyun.player.bean.ErrorInfo errorInfo) {
        //鉴权过期
        if (errorInfo.getCode().getValue() == ErrorCode.ERROR_SERVER_POP_UNKNOWN.getValue()) {
            mIsTimeExpired = true;
        }
        Map<String, Object> params = new HashMap<>();
        //目前uni限制 参数需要放入到"detail"中 否则会被清理
        params.put("detail", errorInfo);
        fireEvent("onError", params);
    }

    /**
     * 字幕、清晰度、码率、音轨点击事件
     */
    private static class MyOnTrackInfoClickListener implements ControlView.OnTrackInfoClickListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnTrackInfoClickListener(XmAliyunVodPlayerView activity) {
            weakReference = new WeakReference<>(activity);
        }

        //字幕
        @Override
        public void onSubtitleClick(List<TrackInfo> subtitleTrackInfoList) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onSubtitleClick(subtitleTrackInfoList);
            }
        }

        //音轨
        @Override
        public void onAudioClick(List<TrackInfo> audioTrackInfoList) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onAudioClick(audioTrackInfoList);
            }
        }

        //码率
        @Override
        public void onBitrateClick(List<TrackInfo> bitrateTrackInfoList) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onBitrateClick(bitrateTrackInfoList);
            }
        }

        //清晰度
        @Override
        public void onDefinitionClick(List<TrackInfo> definitionTrackInfoList) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onDefinitionClick(definitionTrackInfoList);
            }
        }
    }

    /**
     * 字幕改变事件
     */
    private void onSubtitleClick(List<TrackInfo> subtitleTrackInfoList) {
        showMoreDialog = new AlivcShowMoreDialog(mUniSDKInstance.getContext());
        final TrackInfoView mTrackInfoView = new TrackInfoView(mUniSDKInstance.getContext());
        mTrackInfoView.setTrackInfoLists(subtitleTrackInfoList);
        mTrackInfoView.setCurrentTrackInfo(mAliyunVodPlayerView.currentTrack(TrackInfo.Type.TYPE_SUBTITLE));
        showMoreDialog.setContentView(mTrackInfoView);
        showMoreDialog.show();

        mTrackInfoView.setOnSubtitleChangedListener(new TrackInfoView.OnSubtitleChangedListener() {
            @Override
            public void onSubtitleChanged(TrackInfo selectTrackInfo) {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.selectTrack(selectTrackInfo);
                }
            }

            @Override
            public void onSubtitleCancel() {
//                Toast.makeText(mUniSDKInstance.getContext(), R.string.alivc_player_cancel_subtitle, Toast.LENGTH_SHORT).show();
                if (mAliyunVodPlayerView != null) {
//                    mAliyunVodPlayerView.cancelSubtitle();
                }
            }
        });
    }

    /**
     * 音轨改变事件
     */
    private void onAudioClick(List<TrackInfo> audioTrackInfoList) {
        showMoreDialog = new AlivcShowMoreDialog(mUniSDKInstance.getContext());
        final TrackInfoView mTrackInfoView = new TrackInfoView(mUniSDKInstance.getContext());
        mTrackInfoView.setTrackInfoLists(audioTrackInfoList);
        mTrackInfoView.setCurrentTrackInfo(mAliyunVodPlayerView.currentTrack(TrackInfo.Type.TYPE_AUDIO));
        showMoreDialog.setContentView(mTrackInfoView);
        showMoreDialog.show();

        mTrackInfoView.setOnAudioChangedListener(new TrackInfoView.OnAudioChangedListener() {
            @Override
            public void onAudioChanged(TrackInfo selectTrackInfo) {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.selectTrack(selectTrackInfo);
                }
            }
        });
    }

    /**
     * 码率改变事件
     */
    private void onBitrateClick(List<TrackInfo> bitrateTrackInfoList) {
        showMoreDialog = new AlivcShowMoreDialog(mUniSDKInstance.getContext());
        final TrackInfoView mTrackInfoView = new TrackInfoView(mUniSDKInstance.getContext());
        mTrackInfoView.setTrackInfoLists(bitrateTrackInfoList);
        mTrackInfoView.setCurrentTrackInfo(mAliyunVodPlayerView.currentTrack(TrackInfo.Type.TYPE_VIDEO));
        showMoreDialog.setContentView(mTrackInfoView);
        showMoreDialog.show();

        mTrackInfoView.setOnBitrateChangedListener(new TrackInfoView.OnBitrateChangedListener() {
            @Override
            public void onBitrateChanged(TrackInfo selectTrackInfo, int checkedId) {
                if (mAliyunVodPlayerView != null) {
                    if (checkedId == R.id.auto_bitrate) {
                        mAliyunVodPlayerView.selectAutoBitrateTrack();
                    } else {
                        mAliyunVodPlayerView.selectTrack(selectTrackInfo);
                    }
                }
            }
        });
    }

    /**
     * 清晰度改变事件
     */
    private void onDefinitionClick(List<TrackInfo> definitionTrackInfoList) {
        showMoreDialog = new AlivcShowMoreDialog(mUniSDKInstance.getContext());
        final TrackInfoView mTrackInfoView = new TrackInfoView(mUniSDKInstance.getContext());
        mTrackInfoView.setTrackInfoLists(definitionTrackInfoList);
        mTrackInfoView.setCurrentTrackInfo(mAliyunVodPlayerView.currentTrack(TrackInfo.Type.TYPE_VOD));
        showMoreDialog.setContentView(mTrackInfoView);
        showMoreDialog.show();

        mTrackInfoView.setOnDefinitionChangedListener(new TrackInfoView.OnDefinitionChangedListrener() {
            @Override
            public void onDefinitionChanged(TrackInfo selectTrackInfo) {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.selectTrack(selectTrackInfo);
                }
            }
        });
    }

    private static class MyOnInfoListener implements IPlayer.OnInfoListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnInfoListener(XmAliyunVodPlayerView aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void onInfo(InfoBean infoBean) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onInfo(infoBean);
            }
        }
    }

    private void onInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.CacheSuccess) {
//            Toast.makeText(mUniSDKInstance.getContext(), R.string.alivc_player_cache_success, Toast.LENGTH_SHORT).show();
        } else if (infoBean.getCode() == InfoCode.CacheError) {
//            Toast.makeText(mUniSDKInstance.getContext(), infoBean.getExtraMsg(), Toast.LENGTH_SHORT).show();
        } else if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
//            Toast.makeText(mUniSDKInstance.getContext(), R.string.alivc_player_switch_to_software_video_decoder, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * sei监听事件
     */
    private static class MyOnSeiDataListener implements IPlayer.OnSeiDataListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnSeiDataListener(XmAliyunVodPlayerView aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void onSeiData(int type, byte[] bytes) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onSeiData(type, bytes);
            }
        }
    }

    private void onSeiData(int type, byte[] bytes) {
        Log.e(TAG, "onSeiData: type = " + type + " data = " + new String(bytes));
    }

    /**
     * TipsView点击监听事件
     */
    private static class MyOnTipClickListener implements TipsView.OnTipClickListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnTipClickListener(XmAliyunVodPlayerView aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void onContinuePlay() {

        }

        @Override
        public void onStopPlay() {

        }

        @Override
        public void onRetryPlay(int errorCode) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                if (errorCode == ErrorCode.ERROR_LOADING_TIMEOUT.getValue()) {
                    aliyunPlayerSkinActivity.mAliyunVodPlayerView.reTry();
                } else {
                    aliyunPlayerSkinActivity.refresh(false);
                }
            }
        }

        @Override
        public void onReplay() {

        }

        @Override
        public void onRefreshSts() {

        }

        @Override
        public void onWait() {

        }

        @Override
        public void onExit() {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                // TODO: 2021/6/2 0002 这里不能finish
//                aliyunPlayerSkinActivity.finish();
            }
        }
    }

    /**
     * 重试
     */
    private void refresh(final boolean isDownload) {
        if (GlobalPlayerConfig.mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.STS) {
            GetAuthInformation getAuthInformation = new GetAuthInformation();
            getAuthInformation.getVideoPlayStsInfo(new GetAuthInformation.OnGetStsInfoListener() {
                @Override
                public void onGetStsError(String errorMsg) {
//                    ToastUtils.show(mUniSDKInstance.getContext(), errorMsg);
                }

                @Override
                public void onGetStsSuccess(AliyunSts.StsBean dataBean) {
                    if (dataBean != null) {
                        GlobalPlayerConfig.mStsAccessKeyId = dataBean.getAccessKeyId();
                        GlobalPlayerConfig.mStsSecurityToken = dataBean.getSecurityToken();
                        GlobalPlayerConfig.mStsAccessKeySecret = dataBean.getAccessKeySecret();

//                        VidSts vidSts = getVidSts(mCurrentVideoId);
//                        if (isDownload) {
//                            mAliyunDownloadManager.setmVidSts(vidSts);
//                            mAliyunDownloadManager.prepareDownload(vidSts);
//                        } else {
//                            if (mAliyunVodPlayerView != null) {
//                                mAliyunVodPlayerView.setVidSts(vidSts);
//                            }
//                        }

                    }
                }
            });
        } else if (GlobalPlayerConfig.mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.AUTH) {
            GetAuthInformation getAuthInformation = new GetAuthInformation();
            getAuthInformation.getVideoPlayAuthInfo(new GetAuthInformation.OnGetPlayAuthInfoListener() {
                @Override
                public void onGetPlayAuthError(String msg) {
//                    ToastUtils.show(mUniSDKInstance.getContext(), msg);
                }

                @Override
                public void onGetPlayAuthSuccess(AliyunPlayAuth.PlayAuthBean dataBean) {
                    if (dataBean != null) {
                        GlobalPlayerConfig.mPlayAuth = dataBean.getPlayAuth();

//                        VidAuth vidAuth = getVidAuth(mCurrentVideoId);
//                        if (isDownload) {
//                            mAliyunDownloadManager.setmVidAuth(vidAuth);
//                            mAliyunDownloadManager.prepareDownload(vidAuth);
//                        } else {
//                            if (mAliyunVodPlayerView != null) {
//                                mAliyunVodPlayerView.setAuthInfo(vidAuth);
//                            }
//                        }

                    }
                }
            });
        } else if (GlobalPlayerConfig.mCurrentPlayType == GlobalPlayerConfig.PLAYTYPE.MPS) {
            GetAuthInformation getAuthInformation = new GetAuthInformation();
            getAuthInformation.getVideoPlayMpsInfo(new GetAuthInformation.OnGetMpsInfoListener() {
                @Override
                public void onGetMpsError(String msg) {
//                    ToastUtils.show(mUniSDKInstance.getContext(), msg);
                }

                @Override
                public void onGetMpsSuccess(AliyunMps.MpsBean dataBean) {
                    if (dataBean != null) {
                        GlobalPlayerConfig.mMpsRegion = dataBean.getRegionId();
                        GlobalPlayerConfig.mMpsAuthInfo = dataBean.getAuthInfo();
                        GlobalPlayerConfig.mMpsHlsUriToken = dataBean.getHlsUriToken();
                        GlobalPlayerConfig.mMpsAccessKeyId = dataBean.getAkInfo().getAccessKeyId();
                        GlobalPlayerConfig.mMpsSecurityToken = dataBean.getAkInfo().getSecurityToken();
                        GlobalPlayerConfig.mMpsAccessKeySecret = dataBean.getAkInfo().getAccessKeySecret();

//                        VidMps vidMps = getVidMps(mCurrentVideoId);
//                        if (mAliyunVodPlayerView != null) {
//                            mAliyunVodPlayerView.setVidMps(vidMps);
//                        }
                    }
                }
            });
        } else {
            if (mAliyunVodPlayerView != null) {
                mAliyunVodPlayerView.reTry();
            }
        }
    }

    /**
     * TipsView返回按钮点击事件
     */
    private static class MyOnTipsViewBackClickListener implements OnTipsViewBackClickListener {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnTipsViewBackClickListener(XmAliyunVodPlayerView aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void onBackClick() {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.onTipsViewClick();
            }
        }
    }

    private void onTipsViewClick() {
        // TODO: 2021/6/2 0002 不能直接finish
//        finish();
    }

    private static class MyOnVerifyStsCallback implements AliPlayer.OnVerifyTimeExpireCallback {

        private WeakReference<XmAliyunVodPlayerView> weakReference;

        public MyOnVerifyStsCallback(XmAliyunVodPlayerView aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public AliPlayer.Status onVerifySts(StsInfo stsInfo) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                return aliyunPlayerSkinActivity.onVerifySts(stsInfo);
            }
            return AliPlayer.Status.Valid;
        }

        @Override
        public AliPlayer.Status onVerifyAuth(VidAuth vidAuth) {
            XmAliyunVodPlayerView aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                return aliyunPlayerSkinActivity.onVerifyAuth(vidAuth);
            }
            return AliPlayer.Status.Valid;
        }
    }

    private AliPlayer.Status onVerifyAuth(final VidAuth vidAuth) {
        Log.e(TAG, "onVerifyAuth: ");
        String mLiveExpiration = GlobalPlayerConfig.mLiveExpiration;
        long expirationInGMTFormat = TimeFormater.getExpirationInGMTFormat(mLiveExpiration);
        //判断鉴权信息是否过期
        if (TextUtils.isEmpty(mLiveExpiration) || DateUtil.getFixedSkewedTimeMillis() / 1000 > expirationInGMTFormat - 5 * 60) {
            GetAuthInformation getAuthInformation = new GetAuthInformation();
            getAuthInformation.getVideoPlayAuthInfo(new GetAuthInformation.OnGetPlayAuthInfoListener() {
                @Override
                public void onGetPlayAuthError(String msg) {
                    if (mAliyunVodPlayerView != null) {
                        mAliyunVodPlayerView.onStop();
                    }
//                    ToastUtils.show(mUniSDKInstance.getContext(), "Get Auth Info error : " + msg);
                }

                @Override
                public void onGetPlayAuthSuccess(AliyunPlayAuth.PlayAuthBean dataBean) {
                    if (dataBean != null) {
                        GlobalPlayerConfig.mLivePlayAuth = dataBean.getPlayAuth();
                        if (mAliyunVodPlayerView != null) {
                            vidAuth.setPlayAuth(GlobalPlayerConfig.mLivePlayAuth);
                            mAliyunVodPlayerView.updateAuthInfo(vidAuth);
                        }
                    }
                }
            });
            Log.e(TAG, "refreshAuth: ");
            return AliPlayer.Status.Pending;
        } else {
            Log.e(TAG, "IPlayer.AuthStatus.Valid: ");
            return AliPlayer.Status.Valid;
        }
    }

    private AliPlayer.Status onVerifySts(final StsInfo stsInfo) {
        Log.e(TAG, "onVerifySts: ");
        String mLiveExpiration = GlobalPlayerConfig.mLiveExpiration;
        long expirationInGMTFormat = TimeFormater.getExpirationInGMTFormat(mLiveExpiration);
        //判断鉴权信息是否过期
        if (TextUtils.isEmpty(mLiveExpiration) || DateUtil.getFixedSkewedTimeMillis() / 1000 > expirationInGMTFormat - 5 * 60) {
            GetAuthInformation getAuthInformation = new GetAuthInformation();
            getAuthInformation.getVideoPlayLiveStsInfo(new GetAuthInformation.OnGetStsInfoListener() {
                @Override
                public void onGetStsError(String msg) {
                    if (mAliyunVodPlayerView != null) {
                        mAliyunVodPlayerView.onStop();
                    }
//                    ToastUtils.show(mUniSDKInstance.getContext(), "Get Sts Info error : " + msg);
                }

                @Override
                public void onGetStsSuccess(AliyunSts.StsBean dataBean) {
                    if (dataBean != null) {
                        GlobalPlayerConfig.mLiveStsAccessKeyId = dataBean.getAccessKeyId();
                        GlobalPlayerConfig.mLiveStsSecurityToken = dataBean.getSecurityToken();
                        GlobalPlayerConfig.mLiveStsAccessKeySecret = dataBean.getAccessKeySecret();
                        GlobalPlayerConfig.mLiveExpiration = dataBean.getExpiration();

                        if (mAliyunVodPlayerView != null) {
                            stsInfo.setAccessKeyId(GlobalPlayerConfig.mLiveStsAccessKeyId);
                            stsInfo.setAccessKeySecret(GlobalPlayerConfig.mLiveStsAccessKeySecret);
                            stsInfo.setSecurityToken(GlobalPlayerConfig.mLiveStsSecurityToken);
                            mAliyunVodPlayerView.updateStsInfo(stsInfo);
                        }
                    }
                }
            });
            Log.e(TAG, "refreshSts: ");
            return AliPlayer.Status.Pending;
        } else {
            Log.e(TAG, "IPlayer.StsStatus.Valid: ");
            return AliPlayer.Status.Valid;
        }
    }

    @UniJSMethod(uiThread = true)
    public void enterFullScreen() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.enterFullScreen();
        }
    }

    @UniJSMethod(uiThread = true)
    public void exitFullScreen() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.exitFullScreen();
        }
    }

    @UniJSMethod(uiThread = true)
    public void seekTo(JSONObject options) {
        if (options == null || options.isEmpty()) {
            return;
        }
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.seekTo(options.getIntValue("position"));
        }
    }

    @UniJSMethod(uiThread = true)
    public void stopPlay() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.stop();
        }
    }

    @UniJSMethod(uiThread = true)
    public void pausePlay() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.pause();
        }
    }

    @UniJSMethod(uiThread = true)
    public void play() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.start();
        }
    }

    @UniJSMethod(uiThread = true)
    public void replay() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.rePlay();
        }
    }

    @UniJSMethod(uiThread = true)
    public void setDataSource(JSONObject options) {
        if (options == null || options.isEmpty()) {
            Map<String, Object> params = new HashMap<>();
            //目前uni限制 参数需要放入到"detail"中 否则会被清理
            params.put("detail", "UrlSource配置为空！");
            fireEvent("onError", params);
        }
        String videoPath = options.getString("url");
        if (TextUtils.isEmpty(videoPath)) {
            Map<String, Object> params = new HashMap<>();
            //目前uni限制 参数需要放入到"detail"中 否则会被清理
            params.put("detail", "UrlSource地址为空！");
            fireEvent("onError", params);
            return;
        }
        UrlSource urlSource = new UrlSource();
        urlSource.setCoverPath(options.getString("cover"));
        urlSource.setTitle(options.getString("title"));
        mCurrentVideoId = "";

        if (TextUtils.isEmpty(videoPath)) {
            urlSource.setUri(GlobalPlayerConfig.mUrlPath);
        } else {
            urlSource.setUri(videoPath);
        }
        mAliyunVodPlayerView.setLocalSource(urlSource);
        if (!TextUtils.isEmpty(urlSource.getCoverPath())) {
            mAliyunVodPlayerView.setCoverUri(urlSource.getCoverPath());
        }
        if (!TextUtils.isEmpty(urlSource.getTitle())) {
            mAliyunVodPlayerView.setTitleBarCanShow(true);
        }
    }

//    @Override
//    public void onActivityPause() {
//        super.onActivityPause();
//        if (!GlobalPlayerConfig.PlayConfig.mEnablePlayBackground) {
//            if (mAliyunVodPlayerView != null) {
//                mAliyunVodPlayerView.setAutoPlay(true);
//                mAliyunVodPlayerView.onResume();
//            }
//        }
//    }
//
//    @Override
//    public void onActivityStop() {
//        super.onActivityStop();
//        if (!GlobalPlayerConfig.PlayConfig.mEnablePlayBackground) {
//            if (mAliyunVodPlayerView != null) {
//                mAliyunVodPlayerView.setAutoPlay(false);
//                mAliyunVodPlayerView.onStop();
//            }
//        }
//    }

    @Override
    public void onActivityResume() {
        super.onActivityResume();
    }

    @Override
    public void onActivityDestroy() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.onDestroy();
            mAliyunVodPlayerView = null;
        }
    }
}
